package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.assist;

import android.text.TextUtils;

import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.local.sp.CacheUtils;


/**
 * Created by godliness on 2017/8/14.
 * 缓存课程结构
 */

public final class CourseCache {

    public static final String TAG = "CourseCache";

    private static final String INDEX = "1q2w3e4r5t6y7u8i9o0p";

    private static final String USER_ID = UserInfor.getInstance().getUserid();
    private static final StringBuilder mStr = new StringBuilder();

    public interface Flag {

        /**
         * 课程详情页
         */
        String FLAG_FROM_COURSE_DETAIL = "from_course_detail";

        /**
         * 下载详情页
         */
        String FLAG_FROM_COURSE_DOWNLOADED = "from_course_downloaded";

    }

    /**
     * 目前在bb项目中该任务处于子线程中调用
     * @param key            该参数一般传递courseid
     * @param value          课程数据结构
     * @param valueFromWhere key来源于课程详情或者已缓存课程详情
     *                       根据keyFromWhere保存数据，主要区分课程详情页与已缓存课程详情页
     */
    public static boolean cacheToLocal(String key, String value, String valueFromWhere) {
        if (strIsEmpty(key) || strIsEmpty(value)) {
            return false;
        }
        try {
            String cacheKey = generateKey(key, valueFromWhere);
            CacheUtils.setString(cacheKey, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @param key          该参数一般为courseid
     * @param keyFromWhere key来源于课程详情或者已缓存课程详情
     *                     根据keyFromWhere获取数据，主要区分课程详情页与已缓存课程详情页
     */
    public static String cacheFromLocal(String key, String keyFromWhere) {
        if (strIsEmpty(key)) {
            return null;
        }
        String value = null;
        try {
            String cacheKey = generateKey(key, keyFromWhere);
            value = CacheUtils.getString(cacheKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * @param flagFromWhere Flag.FROM_COURSE_DETAIL | Flag.FROM_COURSE_DOWNLOADED
     */
    public static void setCacheFlag(String flagFromWhere) {
        CacheUtils.setString(INDEX, flagFromWhere);
    }

    /**
     * @return Flag.FROM_COURSE_DETAIL | Flag.FROM_COURSE_DOWNLOADED
     */
    public static String getCacheFlag() {
        return CacheUtils.getString(INDEX);
    }

    /**
     * @param key          该参数一般传递courseid
     * @param keyFromWhere key来源于课程详情或者已缓存课程详情
     *                     根据keyFromWhere生成对应key，主要区分课程详情与已缓存课程详情
     */
    private static String generateKey(String key, String keyFromWhere) {
        mStr.setLength(0);
        mStr.append(USER_ID).append(key).append(INDEX).append(keyFromWhere);
        return mStr.toString();
    }

    private static boolean strIsEmpty(String value) {
        return TextUtils.isEmpty(value);
    }

}
